/**
 * 可编辑双表头页面展示
 * @author SPY
 * @date 2020/02/02
 */

import React from 'react';
import { Table, Input, InputNumber, Popconfirm, Form } from 'antd';
import PropTypes from 'prop-types';
import _ from 'lodash';

import styles from './EditTable.less';

const EditableContext = React.createContext();

class EditableCell extends React.Component {
    getInput = () => {
        if (this.props.inputType === 'number') {
            return <InputNumber />;
        }
        return <Input />;
        // return <InputNumber />;
    };

    renderCell = ({ getFieldDecorator }) => {
        const {
            editing,
            dataIndex,
            title,
            inputType,
            record,
            index,
            children,
            ...restProps
        } = this.props;
        return (
            <td {...restProps}>
                {editing ? (
                    <Form.Item style={{ margin: 0 }}>
                        {getFieldDecorator(dataIndex, {
                            rules: [
                                {
                                    required: true,
                                    message: `请输入 ${title}!`,
                                },
                            ],
                            initialValue: record[dataIndex],
                        })(this.getInput())}
                    </Form.Item>
                ) : (
                        children
                    )}
            </td>
        );
    };

    render() {
        return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
    }
}

class EditableTable extends React.Component {

    static propTypes = {
        data: PropTypes.array,  // 要显示的列表
    }

    static defaultProps = {
        data: [],
    }

    static getDerivedStateFromProps(nextProps, prevState) {
        const { data } = nextProps;
        // 当传入的type发生变化的时候，更新state
        if (!_.isEqual(data, prevState.data)) {
            return {
                data,
            };
        }
        // 否则，对于state不进行任何操作
        return null;
    }

    columns = [
        {
            title: ' ',
            dataIndex: 'leftTitle',
            width: '12%',
            align: 'center',
            className: styles.leftTitle,
        },
        {
            title: '班主任姓名',
            dataIndex: 'name',
            width: '25%',
            align: 'center',
            editable: true,
        },
        {
            title: '一本上线人数',
            dataIndex: 'oneCount',
            width: '15%',
            align: 'center',
            editable: true,
        },
        {
            title: '二本上线人数',
            dataIndex: 'twoCount',
            width: '15%',
            align: 'center',
            editable: true,
        },
        {
            title: '三本上线人数',
            dataIndex: 'threeCount',
            width: '15%',
            align: 'center',
            editable: true,
        },
        {
            title: '操 作',
            dataIndex: 'operation',
            align: 'center',
            render: (text, record) => {
                const { editingKey } = this.state;
                const {isEdit} = this.props;
                
                const editable = this.isEditing(record);
                console.log(isEdit,editingKey !== '');
                return editable ? (
                    <span>
                        <EditableContext.Consumer>
                            {form => (
                                <a
                                    onClick={() => this.save(form, record.key)}
                                    style={{ marginRight: 8 }}
                                >
                                    保存
                                </a>
                            )}
                        </EditableContext.Consumer>
                        <Popconfirm title="确定取消吗?" onConfirm={() => this.cancel(record.key)} okText='确定' cancelText='取消'>
                            <a>取消</a>
                        </Popconfirm>
                    </span>
                ) : (
                        <a disabled={!isEdit || editingKey !== ''} onClick={() => this.edit(record.key)}>
                            编辑
                        </a>
                    );
            },
        },
    ];

    state = {
        data: [],
        editingKey: ''
    };



    isEditing = record => {
        const { editingKey } = this.state;
        return record.key === editingKey;
    };

    cancel = () => {
        this.setState({ editingKey: '' });
    };

    save(form, key) {
        form.validateFields((error, row) => {
            if (error) {
                return;
            }
            const { data } = this.state;
            const newData = [...data];
            const index = newData.findIndex(item => key === item.key);
            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, {
                    ...item,
                    ...row,
                });
                this.setState({ editingKey: '' }, () => {
                    const { onChange } = this.props;
                    if (typeof onChange === 'function') {
                        onChange(newData);
                    }
                });
            } else {
                newData.push(row);
                this.setState({ editingKey: '' }, () => {
                    const { onChange } = this.props;
                    if (typeof onChange === 'function') {
                        onChange(newData);
                    }
                });
            }
        });
    }

    edit(key) {
        this.setState({ editingKey: key });
    }

    render() {
        const components = {
            body: {
                cell: EditableCell,
            },
        };

        const columns = this.columns.map(col => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: record => ({
                    record,
                    inputType: col.dataIndex === "name" ? 'text' : 'number',
                    dataIndex: col.dataIndex,
                    title: col.title,
                    editing: this.isEditing(record),
                }),
            };
        });

        const { data } = this.state;

        return (
            <EditableContext.Provider value={this.props.form}>
                <Table
                    components={components}
                    bordered
                    dataSource={data}
                    columns={columns}
                    //   rowClassName="editable-row"
                    pagination={false}
                />
            </EditableContext.Provider>
        );
    }
}

const EditableFormTable = Form.create()(EditableTable);

export default EditableFormTable;